package com.sunday.pinxinghui.adapter;

import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.Paint;
import android.support.v4.content.ContextCompat;
import android.support.v7.widget.RecyclerView;
import android.text.SpannableStringBuilder;
import android.text.Spanned;
import android.text.TextUtils;
import android.text.style.BackgroundColorSpan;
import android.text.style.ForegroundColorSpan;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.sunday.common.event.EventBus;
import com.sunday.common.model.ResultDO;
import com.sunday.common.utils.ToastUtils;
import com.sunday.common.widgets.NoScrollGridView;
import com.sunday.common.widgets.banner.ConvenientBanner;
import com.sunday.pinxinghui.R;
import com.sunday.pinxinghui.base.BaseApplication;
import com.sunday.pinxinghui.entity.IndexCategory;
import com.sunday.pinxinghui.entity.Product;
import com.sunday.pinxinghui.entity.ProductCategory;
import com.sunday.pinxinghui.event.UpdateCartNum;
import com.sunday.pinxinghui.model.products.ProductDetailActivity;

import com.sunday.pinxinghui.model.products.ProductsListActivity;
import com.sunday.pinxinghui.network.ApiClient;

import java.math.RoundingMode;
import java.util.List;

import butterknife.Bind;
import butterknife.ButterKnife;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

/**
 * Created by 刘涛 on 2017/8/15.
 */

public class IndexProductListAdapter extends RecyclerView.Adapter {


    private Context mContext;
    private final static int TYPE_HEAD = 0;
    private final static int TYPE_LIST = 1;
    private List<Product> dataSet;
    private List<IndexCategory> productClassifyList;
    private LayoutInflater inflater;
    private CategoryAdapter categoryAdapter;
    private String parentName;
    private int parentId;

    public IndexProductListAdapter(Context context, List<Product> datas,
                                   List<IndexCategory> productClassifies, String parentName, int parentId) {
        this.mContext = context;
        this.dataSet = datas;
        this.productClassifyList = productClassifies;
        this.parentName = parentName;
        this.parentId = parentId;
        inflater = LayoutInflater.from(mContext);
    }

    @Override
    public int getItemViewType(int position) {
        if (position == 0) {
            return TYPE_HEAD;
        } else {
            return TYPE_LIST;
        }
    }

    @Override
    public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        switch (viewType) {
            case TYPE_HEAD:
                View view = inflater.inflate(R.layout.index_product_category_list, null);
                RecyclerView.LayoutParams params = new RecyclerView.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
                //params.setMargins(0,0,0,3);
                view.setLayoutParams(params);
                return new HeadHolder(view);
            case TYPE_LIST:
                view = inflater.inflate(R.layout.layout_product_list_item, null);
                return new ProductHolder(view);
        }
        return null;
    }

    @Override
    public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {
        switch (getItemViewType(position)) {
            case TYPE_HEAD:
                HeadHolder productCategortyHolder = (HeadHolder) holder;
                if (productClassifyList != null && productClassifyList.size() > 0) {
                    ((HeadHolder) holder).gridView.setVisibility(View.VISIBLE);
                    categoryAdapter = new CategoryAdapter(mContext, productClassifyList);
                    productCategortyHolder.gridView.setAdapter(categoryAdapter);
                    categoryAdapter.notifyDataSetChanged();
                    productCategortyHolder.gridView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                        @Override
                        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                            IndexCategory productBrand = (IndexCategory) parent.getAdapter().getItem(position);
                            //Intent intent = new Intent(mContext, ProductListActivity.class);
                            Intent intent = new Intent(mContext, ProductsListActivity.class);
                            intent.putExtra("parentName", parentName);
                            intent.putExtra("parentId", parentId);
                            intent.putExtra("catId", productBrand.getId());
                            mContext.startActivity(intent);
                        }
                    });
                } else {
                    ((HeadHolder) holder).gridView.setVisibility(View.GONE);
                }
                break;
            case TYPE_LIST:
                ProductHolder productHolder = (ProductHolder) holder;
                Product item = dataSet.get(position - 1);
                if (!TextUtils.isEmpty(item.getImage())) {
                    Glide.with(mContext)
                            .load(item.getImage())
                            .error(R.mipmap.ic_default)
                            .into(productHolder.productImg);
                }
                productHolder.productTitle.setText(item.getProductName());
                productHolder.saleNum.setText("销量" + item.getSaleCount());
                productHolder.priceOld.setText(String.format("市价¥%s", item.getCostPrice().setScale(2, RoundingMode.HALF_UP)));
                productHolder.priceOld.getPaint().setFlags(Paint.STRIKE_THRU_TEXT_FLAG | Paint.ANTI_ALIAS_FLAG);
                productHolder.sellOutImg.setVisibility(item.getStore() == 0 ? View.VISIBLE : View.GONE);
                switch (item.getType()) {
                    case 1:
                        //普通商品
                        productHolder.flagImg.setVisibility(View.GONE);
                        productHolder.priceNow.setText(String.format("会员价:¥%s", item.getVipPrice().setScale(2, RoundingMode.HALF_UP)));
                        break;
                    case 2:
                        //秒杀产品
                        productHolder.flagImg.setVisibility(View.VISIBLE);
                        productHolder.flagImg.setImageResource(R.mipmap.miaosha);
                        productHolder.priceNow.setText(String.format("秒杀价:¥%s", item.getPrice().setScale(2, RoundingMode.HALF_UP)));
                        break;
                    case 3:
                        //限时购商品
                        productHolder.flagImg.setVisibility(View.VISIBLE);
                        productHolder.flagImg.setImageResource(R.mipmap.qianggou);
                        productHolder.priceNow.setText(String.format("抢购价:¥%s", item.getPrice().setScale(2, RoundingMode.HALF_UP)));
                        break;
                }

                productHolder.totalLayout.setTag(item);
                productHolder.btnBuy.setTag(item);
                break;
        }

    }

    class HeadHolder extends RecyclerView.ViewHolder {
        @Bind(R.id.grid_view)
        NoScrollGridView gridView;

        public HeadHolder(View itemView) {
            super(itemView);
            ButterKnife.bind(this, itemView);
        }
    }

    class ProductHolder extends RecyclerView.ViewHolder implements View.OnClickListener {

        @Bind(R.id.product_img)
        ImageView productImg;
        @Bind(R.id.flag_img)
        ImageView flagImg;
        @Bind(R.id.product_title)
        TextView productTitle;
        @Bind(R.id.sale_num)
        TextView saleNum;
        @Bind(R.id.price_old)
        TextView priceOld;
        @Bind(R.id.price_now)
        TextView priceNow;
        @Bind(R.id.total_layout)
        RelativeLayout totalLayout;
        @Bind(R.id.sell_out_img)
        ImageView sellOutImg;
        @Bind(R.id.btn_buy)
        ImageView btnBuy;

        public ProductHolder(View itemView) {
            super(itemView);
            ButterKnife.bind(this, itemView);
            totalLayout.setOnClickListener(this);
            btnBuy.setOnClickListener(this);

        }

        @Override
        public void onClick(View v) {
            Product item = (Product) v.getTag();
            switch (v.getId()) {
                case R.id.total_layout:
                    Intent intent = new Intent(mContext, ProductDetailActivity.class);
                    intent.putExtra("type", item.getType());
                    intent.putExtra("productId", item.getProductId());
                    mContext.startActivity(intent);
                    break;
                case R.id.btn_buy:
                    addCart(item.getProductId());
                    break;
            }

        }
    }

    private void addCart(long productId) {
        Call<ResultDO> call = ApiClient.getApiAdapter().addCart(productId, BaseApplication.getInstance().getMember().getId(), null, 1);
        call.enqueue(new Callback<ResultDO>() {
            @Override
            public void onResponse(Call<ResultDO> call, Response<ResultDO> response) {
                if (response.body() == null) {
                    return;
                }
                if (response.body().getCode() == 0) {
                    ToastUtils.showToast(mContext, "成功加入购物车");
                    EventBus.getDefault().post(new UpdateCartNum());
                } else {
                    ToastUtils.showToast(mContext, response.body().getMessage());
                }
            }

            @Override
            public void onFailure(Call<ResultDO> call, Throwable t) {
                ToastUtils.showToast(mContext, R.string.network_error);
            }
        });
    }


    @Override
    public int getItemCount() {
        return dataSet.size() + 1;
    }
}
